#include <iostream>
#include "Sock.hpp"
#include "Protocol.hpp"

using namespace NS_Protocol;

void Usage(const std::string& proc)
{
    std::cout << "Usage: " << proc << " <IP> <Port>" << std::endl;
}

std::string buffer;
int main(int argc, char* argv[])
{
    if(argc != 3)
    {
        Usage(argv[0]);
        exit(1);
    }

    std::string server_ip = argv[1];
    uint16_t server_port = atoi(argv[2]);

    Sock sock;
    int sockfd = sock.Socket();
    if(!sock.Connect(sockfd, server_ip, server_port))
    {
        std::cerr << "connect error" << std::endl;
        exit(2);
    }

    bool quit = false;
    while(!quit)
    {
        // 1. 获取需求
        Request req;
        std::cout << "Please enter# ";
        std::cin >> req._x >> req._op >> req._y;

        // 2. 序列化
        std::string s = req.Serialize();
        // 3. 添加长度报头
        s = Encode(s);
        // 4. 发送到服务端
        Send(sockfd, s);

        // 5. 读取
        while(true)
        {
            bool res = Recv(sockfd, &buffer);
            if(!res) {
                quit = true;
                break;
            }

            // 6. 解码
            std::string s = Decode(buffer);
            // 7. 反序列化
            Response resp;
            resp.Deserialize(s);
            // 7.5 判断 +             // 8. 输出结果
            std::string err;
            switch(resp._code)
            {
            case 1:
                err = "除0错误";
                break;
            case 2:
                err = "模0错误";
                break;
            case 3:
                err = "非法操作";
                break;
            default:
                std::cout << resp._x << " " << resp._op << " " << resp._y << " = " << resp._result << std::endl;
                break;
            }

            break;
        }

        close(sockfd);
        return 0;
    }
}